<?php
namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;
use app\service\TopviewApiService;
use app\constant\ProductBackgroundStatus;

/**
 * 阶段1：轮询去背景任务（status=10），成功后自动提交背景生成任务（置 status=1, template_id=background_v2）
 */
class CheckProductBackgroundTasks extends Command
{
    protected function configure()
    {
        $this->setName('check:product-background')
            ->setDescription('轮询去背景任务并自动提交背景生成');
    }

    protected function execute(Input $input, Output $output)
    {
        $api = new TopviewApiService();
        $output->writeln('开始检查去背景任务...');

        $tasks = Db::name('product_anyshoot_tasks')
            ->where('template_id', 'background_v2_pre')
            ->where('status', ProductBackgroundStatus::PREPROCESSING)
            ->where('task_id', '<>', '')
            ->order('id', 'asc')
            ->limit(50)
            ->select();

        foreach ($tasks as $task) {
            try {
                $output->writeln("检查去背景: {$task['task_id']}");
                $res = $api->queryRemoveBackgroundTask($task['task_id']);
                $status = $res['status'] ?? '';
                if ($status === 'success') {
                    $bgRemovedFileId = $res['bgRemovedImageFileId'] ?? '';
                    if (empty($bgRemovedFileId)) {
                        throw new \Exception('去背景成功但未返回文件ID');
                    }

                    // 组装背景生成参数，继承任务入库时的参数
                    $submitParams = [
                        'productImageFileId' => $task['product_image_file_id'],
                        'productImageWithoutBackgroundFileId' => $bgRemovedFileId,
                        'mode' => $task['mode'] ?? 'advanced',
                        'generatingCount' => intval($task['generating_count'] ?? 1),
                    ];
                    if (!empty($task['template_image_file_id'])) {
                        $submitParams['templateImageFileId'] = $task['template_image_file_id'];
                    }
                    if (!empty($task['template_mask_file_id'])) {
                        $submitParams['templateMaskFileId'] = $task['template_mask_file_id'];
                    }

                    // 提交背景生成
                    $submit = $api->submitProductBackgroundTask($submitParams);
                    $remoteTaskId = $submit['taskId'] ?? ($submit['result']['taskId'] ?? '');
                    if (empty($remoteTaskId)) {
                        throw new \Exception('背景生成提交成功但未返回taskId');
                    }

                    // 更新为背景生成阶段
                    Db::name('product_anyshoot_tasks')
                        ->where('id', $task['id'])
                        ->update([
                            'task_id' => $remoteTaskId,
                            'template_id' => 'background_v2',
                            'status' => ProductBackgroundStatus::GENERATING,
                            'update_time' => date('Y-m-d H:i:s')
                        ]);

                    $output->writeln("已提交背景生成: {$remoteTaskId}");
                } elseif ($status === 'failed') {
                    Db::name('product_anyshoot_tasks')
                        ->where('id', $task['id'])
                        ->update([
                            'status' => ProductBackgroundStatus::FAILED,
                            'update_time' => date('Y-m-d H:i:s')
                        ]);
                    $output->writeln("去背景失败: {$task['task_id']}");
                }
            } catch (\Exception $e) {
                $output->writeln('处理失败: ' . $e->getMessage());
            }
        }

        $output->writeln('检查完成');
        return 0;
    }
}


